package com.atguigu.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * projectName: day04_jdbc
 *
 * @author: 赵伟风
 * time: 2021/11/26 16:01
 * description:批量数据插入
 *
 *    todo： 批处理条件
 *        1.开启批处理 jdbc:mysql:///test1?rewriteBatchedStatements=true
 *        2.values必须
 *        3.每次都添加到处理队列
 *        4.统一执行
 *        批处理成功的状态码是 -2
 */
public class BatchInsert {

    public static void main(String[] args) throws ClassNotFoundException,SQLException {



        //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///test1?rewriteBatchedStatements=true", "root", "root");

        //3.sql结构
        String sql = "insert into user (nickname,account,password) values (?,?,?)";

        //4.预编译动态statement
        //设置想要获取返回生成keys
        PreparedStatement statement = connection.prepareStatement(sql);

        long start = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {


            //5.占位符赋值
            statement.setObject(1, "吴邪"+i);
            statement.setObject(2, "wuxie1"+i);
            statement.setObject(3, "root");

            statement.addBatch();
            //int rows = statement.executeUpdate();
        }

        //6.执行sq
        int[] rows = statement.executeBatch();
        //
        System.out.println(Arrays.toString(rows));


        long end = System.currentTimeMillis();

        System.out.println("time = " + (end - start));



        //7.关闭资源

        statement.close();
        connection.close();
    }


}
